<template>
  <el-dialog title="分配角色" :visible="visible" @close="closeFn" @open="openFn">
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>>

    </el-checkbox-group>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetail } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    employeeId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      checkList: [],
      list: []
    }
  },
  methods: {
    // 点击弹框自身的❌，可触发此函数
    closeFn() {
      this.checkList = []
      this.$emit('update:visible', false)
    },
    openFn() {
      // 接口之间没有先后关系时，并行发送接口请求，节省时间
      // 接口之间有先后关系时，串行
      this.getRoleList()
      this.getUserDetail()
    },
    async getRoleList() {
      const { rows } = await getRoleList()
      this.list = rows
    },
    async getUserDetail() {
      const { roleIds } = await getUserDetail(this.employeeId)
      this.checkList = roleIds || []// 如果返回的是null，赋值一个空数组
    },
    async submit() {
      if (!this.checkList.length) return this.$message.warning('数据不能为空')
      await assignRoles({ id: this.employeeId, roleIds: this.checkList })
      this.$message.success('更新角色成功')
      this.closeFn()
    }

  }
}
</script>
